import { fetchUpload } from '@/api/upload'
import { v4 as uuidv4 } from 'uuid'

const advert = {
  data() {
    return {
      user: {
        username: '',
        password: '',
        avatar: '',
        admin: 1,
        roleId: ''
      },
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 8,
            message: '长度在 2 到 8 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        avatar: [
          {
            required: true,
            message: '请上传美照',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 上传之前
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false

      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名
      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },

    // 上传成功，获取图片地址
    uploadSuccess(res) {
      this.user.avatar = 'https://image.holyzq.com/' + res.key
    }
  }
}

export default advert
